const https = require('https');

class USD_XAU {

  constructor(gap) {

    this.gap = gap || 5000;
    this.price = 0;
    this.interval = 0;
    this.callback = null;
  }
  stop() {
    clearInterval(this.interval);
    this.interval = 0;
  }

  start() {
    if (this.interval) return false;
    this.interval = setInterval(() => {
      https.get('https://data-asg.goldprice.org/dbXRates/USD', {
        "headers": {
          "accept": "application/json, text/javascript, */*; q=0.01",
          "accept-language": "zh-CN,zh;q=0.9",
          "if-none-match": "W/\"15-4x6jtFbbfX3Ei2XqgnWy3Uj+Cek\"",
          "sec-fetch-dest": "empty",
          "sec-fetch-mode": "cors",
          "sec-fetch-site": "same-site"
        },
        "referrer": "https://goldprice.org/",
        "referrerPolicy": "strict-origin-when-cross-origin",
        "body": null,
        "method": "GET",
        "mode": "cors"
      }, (res) => {
        const { statusCode } = res;
        const contentType = res.headers['content-type'];

        let error;
        // Any 2xx status code signals a successful response but
        // here we're only checking for 200.
        if (statusCode !== 200) {
          error = new Error('Request Failed.\n' +
            `Status Code: ${statusCode}`);
        } else if (!/^application\/json/.test(contentType)) {
          error = new Error('Invalid content-type.\n' +
            `Expected application/json but received ${contentType}`);
        }
        if (error) {
          console.error(error.message);
          // Consume response data to free up memory
          res.resume();
          return;
        }

        res.setEncoding('utf8');
        let rawData = '';
        res.on('data', (chunk) => { rawData += chunk; });
        res.on('end', () => {
          try {
            const parsedData = JSON.parse(rawData);
            // console.log('parsedData', parsedData);
            this.price = parsedData.items[0].xauPrice;
            // console.log(this.price);
          } catch (e) {
            console.error('Error in Getting https://data-asg.goldprice.org/GetData/USD-XAU/1 \n', e.message);
          }
        });
      }).on('error', (e) => {
        console.error(`Got error: ${e.message}`);
      });
    }, this.gap);
    return true;
  }
}

module.exports.USD_XAU = USD_XAU;